﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
namespace Admin.NET.Application;

/// <summary>
/// CRM客户服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class CRMCustomerService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<CRMCustomer> _cRMCustomerRep;
    private readonly UserManager _userManager;

    public CRMCustomerService(
        SqlSugarRepository<CRMCustomer> cRMCustomerRep, 
        UserManager userManager
)
    {
        _cRMCustomerRep = cRMCustomerRep;
        _userManager = userManager;
    }

    /// <summary>
    /// 分页查询CRM客户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询CRM客户")]
    public async Task<SqlSugarPagedList<CRMCustomerOutput>> Page(PageCRMCustomerInput input)
    {
        input.SearchKey = input.SearchKey?.Trim();
        if (input.SelectType == 1)
        {
            input.CustLeadId = _userManager.UserId;
        }
        else if (input.SelectType == 2)
        {
            input.CustLeadId = 0;
        }

        var query = _cRMCustomerRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.CustName.Contains(input.SearchKey)
                || u.ContactName.Contains(input.SearchKey)
                || u.MobilePhone.Contains(input.SearchKey)
                || u.Telephone.Contains(input.SearchKey)
                || u.DetailedAddress.Contains(input.SearchKey)
                || u.LastFollowUpRecord.Contains(input.SearchKey)
                || u.Remark.Contains(input.SearchKey)
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.CustName), u => u.CustName.Contains(input.CustName.Trim()))
            .WhereIF(input.CustLeadId > -1, u => u.CustLeadId == input.CustLeadId)
            .WhereIF(input.IsCollect > 0, u => u.IsCollect == input.IsCollect)
            .WhereIF(input.CustomerSource > 0, u => u.CustomerSource.ToString() == input.CustomerSource.ToString())
            //.WhereIF(!string.IsNullOrWhiteSpace(input.ContactName), u => u.ContactName.Contains(input.ContactName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.MobilePhone), u => u.MobilePhone.Contains(input.MobilePhone.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Telephone), u => u.Telephone.Contains(input.Telephone.Trim()))
            .WhereIF(input.CustomerLevel > 0, u => u.CustomerLevel.ToString() == input.CustomerLevel.ToString())
            .WhereIF(input.CustomerStatus > 0, u => u.CustomerStatus.ToString() == input.CustomerStatus.ToString())
            .WhereIF(input.CustomerSpecification > 0, u => u.CustomerSpecification.ToString() == input.CustomerSpecification.ToString())
            //.WhereIF(input.NextContactDateRange != null && input.NextContactDateRange.Length == 2, u => u.NextContactDate >= input.NextContactDateRange[0] && u.NextContactDate <= input.NextContactDateRange[1])
            .Select<CRMCustomerOutput>();
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加CRM客户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加CRM客户")]
    public async Task<long> Add(AddCRMCustomerInput input)
    {
        var entity = input.Adapt<CRMCustomer>();

        if (input.DistrictList != null)
        {
            entity.Province = 0;
            entity.City = 0;
            entity.District = 0;
            if (input.DistrictList.Count() > 0)
                entity.Province = input.DistrictList[0];
            if (input.DistrictList.Count() > 1)
                entity.City = input.DistrictList[1];
            if (input.DistrictList.Count() > 2)
                entity.District = input.DistrictList[2];
        }

        entity.CustLeadId = _userManager.UserId;
        await _cRMCustomerRep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除CRM客户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除CRM客户")]
    public async Task Delete(DeleteCRMCustomerInput input)
    {
        var entity = await _cRMCustomerRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _cRMCustomerRep.FakeDeleteAsync(entity);   //假删除
        //await _cRMCustomerRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新CRM客户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新CRM客户")]
    public async Task Update(UpdateCRMCustomerInput input)
    {
        var entity = input.Adapt<CRMCustomer>();
        if (input.DistrictList != null)
        {
            entity.Province = 0;
            entity.City = 0;
            entity.District = 0;
            if (input.DistrictList.Count() > 0)
                entity.Province = input.DistrictList[0];
            if (input.DistrictList.Count() > 1)
                entity.City = input.DistrictList[1];
            if (input.DistrictList.Count() > 2)
                entity.District = input.DistrictList[2];
        }

        await _cRMCustomerRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取CRM客户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取CRM客户")]
    public async Task<CRMCustomer> Detail([FromQuery] QueryByIdCRMCustomerInput input)
    {
        return await _cRMCustomerRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取CRM客户列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取CRM客户列表")]
    public async Task<List<CRMCustomerOutput>> List([FromQuery] PageCRMCustomerInput input)
    {
        return await _cRMCustomerRep.AsQueryable().Select<CRMCustomerOutput>().ToListAsync();
    }





}
